//
//  Extension+Regex.swift
//  ZDKBaseKit
//
//  Created by Killua on 2017/9/22.
//  Copyright © 2017年 JingZhong. All rights reserved.
//

import Foundation

// MARK: - 正则表达式验证字符串
extension String {

    /// 是否有效的手机号码
    ///
    /// - Returns: Bool
    func isValidMobile() -> Bool {
        let pattern = "^1[3|4|5|7|8][0-9]\\d{8}$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否有效的电话号码
    ///
    /// - Returns: Bool
    func isValidTel() -> Bool {
        let pattern = "^([\\d{3,4}-)\\d{7,8}$](file:///d%7B3,4%7D-)//d%7B7,8%7D$)"
        return matchesPattern(pattern: pattern)
    }

    // MARK: --Public Function--
    /// 是否是有效的邮箱
    ///
    /// - Returns: Bool
    func isValidEmail() -> Bool {
        let pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否有效的身份证
    ///
    /// - Returns: Bool
    func isValidIDCard() -> Bool {
        let pattern = "\\d{14}[[0-9],0-9xX]"
        return matchesPattern(pattern: pattern)
    }

    /// 是否数字和英文字母组成的字符串
    ///
    /// - Returns: Bool
    func isNumbersAndAlphabet() -> Bool {
        let pattern = "^[A-Za-z0-9]+$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否是一个数(整数/小数)
    ///
    /// - Returns: Bool
    func isNumber() -> Bool {
        let pattern = "^[0-9]+([.]{0,1}[0-9]+){0,1}$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否是一个整数
    ///
    /// - Returns: Bool
    func isIntNumber() -> Bool {
        let pattern = "^[0-9]*$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否是汉字
    ///
    /// - Returns: Bool
    func isChineseCharacter() -> Bool {
        let pattern = "^[\\u4e00-\\u9fa5]{0,}$"
        return matchesPattern(pattern: pattern)
    }

    /// 是否是有效的链接
    ///
    /// - Returns: Bool
    func isValidURL() -> Bool {
        let pattern = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"
        return matchesPattern(pattern: pattern)
    }


    // MARK: --Private Function--
    /// 匹配正则表达式
    ///
    /// - Parameter pattern: 正则表达式
    /// - Returns: Bool
    private func matchesPattern(pattern: String) -> Bool {
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let result = regex.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))

        return result.count > 0
    }
}
